const winston = require("winston");
require("winston-daily-rotate-file"); // 引入日志轮转插件
const { format, transports } = winston;
const { combine, timestamp, json } = format;
const fs = require("fs");
const path = require("path");

const logDir = path.join(__dirname, "../logs");

if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir);
}

// 创建按小时轮转的日志传输
const hourlyRotateFileTransport = new transports.DailyRotateFile({
  filename: path.join(logDir, "modbus-logs-%DATE%.log"),
  datePattern: "YYYY-MM-DD-HH", // 按小时轮转
  zippedArchive: false, // 不压缩
  maxSize: "100m", // 单个文件最大100MB
  maxFiles: "10d", // 保留10天的日志
  level: "debug",
});

// 创建按小时轮转的错误日志传输
const hourlyRotateErrorFileTransport = new transports.DailyRotateFile({
  filename: path.join(logDir, "modbus-errors-%DATE%.log"),
  datePattern: "YYYY-MM-DD-HH", // 按小时轮转
  zippedArchive: false, // 不压缩
  maxSize: "100m", // 单个文件最大100MB
  maxFiles: "30d", // 保留30天的日志
  level: "error",
});

const loggers = winston.createLogger({
  level: "debug",
  format: combine(
    timestamp({
      format: () =>
        new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" }),
    }),
    json() // 支持输出对象
  ),
  transports: [
    hourlyRotateErrorFileTransport, // 错误日志按小时轮转
    hourlyRotateFileTransport, // 普通日志按小时轮转
    new transports.Console({ level: "debug" }),
  ],
});

module.exports = loggers;
